package com.example.a001.part08;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

import com.example.a001.R;

public class ProgressBarActivity01 extends AppCompatActivity {
    private ProgressBar progressBar;
    private int progressStatus = 0;
    private Handler handler = new Handler();
    private Switch lightSwitch;
    private ImageView lightImageView;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progress_bar01);

        // 初始化进度条
        progressBar = findViewById(R.id.progressBar);

        // 启动一个线程来更新进度条
        new Thread(new Runnable() {
            public void run() {
                while (progressStatus < 100) {
                    progressStatus += 1;
                    // 向主线程发送消息以更新 UI
                    handler.post(new Runnable() {
                        public void run() {
                            progressBar.setProgress(progressStatus);
                        }
                    });
                    try {
                        // 模拟耗时操作
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        // 初始化 Switch 和 ImageView
        lightSwitch = findViewById(R.id.lightSwitch);
        lightImageView = findViewById(R.id.lightImageView);

        // 设置 Switch 的监听器
        lightSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 灯泡点亮
                lightImageView.setImageResource(R.drawable.on);
            } else {
                // 灯泡关闭
                lightImageView.setImageResource(R.drawable.off);
            }
        });
    }
}
